"""
ＰＢ源码关键字搜索
"""
import os


# 在文件中查找关键字
def FindInFile(key, fname):
    try:
        with open(fname, 'r', errors='ignore') as f:
            res = f.read()
        return key in res
    except BaseException as e:
        return False


#  在文件行中查找关键字
def FindInFIleLine(key, fname):
    try:
        with open(fname, 'r', errors='ignore') as f:
            lines = f.readlines()
        for inx, line in enumerate(lines):
            if key in line: print(f"line:{inx} > {line}")

    except BaseException as e:
        return False


def FindInfolders(key, folders):
    # 遍历所有文件夹
    for folder in folders:
        if not folder[2]: continue  # 文件夹为空
        for file in folder[2]:
            if file[-3:] == "bin": continue  # bin文件跳过
            filePath = f"{folder[0]}\\{file}"
            if FindInFile(key, filePath):
                t = filePath.split("\\")
                pbl = t[-2]
                control = t[-1].split(".")[0]
                print(f"found in [{control}] from [{pbl}.pbl] \n")
                FindInFIleLine(key, filePath)


if __name__ == '__main__':

    # 要检索的文件夹
    path = "d:\\lh_srout_210612\\"
    # 要检索的关键字
    keywords = "f_g_all_excute"

    folders = os.walk(path)
    folders = list(folders)[1:]

    print("\n开始查找! \n")
    FindInfolders(keywords, folders)